#!/usr/bin/env python3
"""
简化的后端启动脚本
仅启动FastAPI服务，使用SQLite数据库
"""
import os
import sys
from pathlib import Path

# 添加项目路径
backend_dir = Path(__file__).parent
sys.path.insert(0, str(backend_dir))

def check_dependencies():
    """检查必要的依赖"""
    required_packages = [
        'fastapi', 'uvicorn', 'sqlalchemy', 'pydantic', 
        'python-jose', 'passlib', 'aiosqlite'
    ]
    
    missing = []
    for package in required_packages:
        try:
            __import__(package.replace('-', '_'))
            print(f"✓ {package} 已安装")
        except ImportError:
            missing.append(package)
            print(f"✗ {package} 未安装")
    
    return missing

def install_dependencies(packages):
    """安装缺失的依赖"""
    if not packages:
        return True
    
    print(f"\n正在安装缺失的依赖: {', '.join(packages)}")
    try:
        import subprocess
        cmd = [sys.executable, '-m', 'pip', 'install'] + packages
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        if result.returncode == 0:
            print("✓ 依赖安装成功")
            return True
        else:
            print(f"✗ 依赖安装失败: {result.stderr}")
            return False
    except Exception as e:
        print(f"✗ 安装过程出错: {e}")
        return False

def main():
    """启动开发服务器"""
    print("=== SmartCity-LLM Trainer 简化启动 ===")
    print("使用SQLite数据库进行快速测试\n")
    
    try:
        # 检查Python版本
        if sys.version_info < (3, 8):
            print("错误: 需要Python 3.8或更高版本")
            input("按回车键退出...")
            return
        
        print(f"Python版本: {sys.version}")
        print(f"工作目录: {backend_dir}\n")
        
        # 检查依赖
        print("检查依赖...")
        missing_deps = check_dependencies()
        
        if missing_deps:
            print(f"\n缺少 {len(missing_deps)} 个依赖包")
            choice = input("是否自动安装? (y/N): ").lower().strip()
            
            if choice in ['y', 'yes']:
                if not install_dependencies(missing_deps):
                    print("依赖安装失败，请手动安装:")
                    print(f"pip install {' '.join(missing_deps)}")
                    input("按回车键退出...")
                    return
            else:
                print("请手动安装缺失的依赖:")
                print(f"pip install {' '.join(missing_deps)}")
                input("按回车键退出...")
                return
        
        # 设置环境变量
        os.environ["DATABASE_URL"] = "sqlite+aiosqlite:///./test.db"
        os.environ["SECRET_KEY"] = "your-secret-key-for-development"
        os.environ["ENVIRONMENT"] = "development"
        
        print("\n环境配置:")
        print(f"DATABASE_URL: {os.environ['DATABASE_URL']}")
        print(f"ENVIRONMENT: {os.environ['ENVIRONMENT']}")
        
        # 检查主应用文件
        main_py = backend_dir / "main.py"
        if not main_py.exists():
            print(f"\n错误: 未找到 {main_py}")
            print("请确保在正确的目录中运行此脚本")
            input("按回车键退出...")
            return
        
        print(f"\n找到主应用文件: {main_py}")
        
        # 启动服务
        print("\n正在启动FastAPI服务器...")
        print("服务地址: http://localhost:8000")
        print("API文档: http://localhost:8000/api/v1/docs")
        print("健康检查: http://localhost:8000/health")
        print("\n按 Ctrl+C 停止服务\n")
        print("=" * 50)
        
        try:
            import uvicorn
            uvicorn.run(
                "main:app",
                host="0.0.0.0",
                port=8000,
                reload=True,
                log_level="info"
            )
        except KeyboardInterrupt:
            print("\n\n=== 服务已停止 ===")
        except Exception as e:
            print(f"\n服务启动失败: {e}")
            print(f"错误类型: {type(e).__name__}")
            import traceback
            print("详细错误信息:")
            traceback.print_exc()
            
    except Exception as e:
        print(f"\n启动过程出现错误: {e}")
        print(f"错误类型: {type(e).__name__}")
        import traceback
        print("详细错误信息:")
        traceback.print_exc()
    
    finally:
        input("\n按回车键退出...")

if __name__ == "__main__":
    main()